/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.common.service.base.event;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.event.EventListener;

/**
 * <b>(ResultLogEventListener)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/6/22
 */
@Slf4j
@Component
public class ResultLogEventListener implements EventListener<ServiceResultLogEvent> {

    @Override
    public void onEvent(ServiceResultLogEvent event) {
        String resultName = "";
        // 如果压根没有Result返回则退出，并打印提醒日志
        if (ObjectUtil.isAllEmpty(event.getResultBase(), event.getSingleResult(), event.getListResult(), event.getPageResult()) && StrUtil.isEmpty(event.getProductCode())) {
            log.error("[{}]请求[{}]出现问题，没有收到Result.", resultName, event.getBizOrderNo());
            return;
        }

        if (ObjectUtil.isNotNull(event.getResultBase())) {
            resultName = event.getResultBase().getClass().getSimpleName();
        }

        if (ObjectUtil.isNotNull(event.getSingleResult())) {
            resultName = event.getSingleResult().getClass().getSimpleName();
        }

        if (ObjectUtil.isNotNull(event.getListResult())) {
            resultName = event.getListResult().getClass().getSimpleName();
        }

        if (ObjectUtil.isNotNull(event.getPageResult())) {
            resultName = event.getPageResult().getClass().getSimpleName();
        }

        if (StrUtil.isNotEmpty(event.getProductCode())) {
            resultName = event.getProductCode();
        }

        // 组装JSON串
        String returnJson = "";
        // 1. 如果有单个对象的Result，则组装单个对象
        if (ObjectUtil.isNotNull(event.getSingleResult())) {
            returnJson = JSON.toJSONString(event.getSingleResult());
        }

        // 2. 如果有多个对象的Result，则组装多个对象
        if (ObjectUtil.isNotNull(event.getListResult())) {
            returnJson = JSON.toJSONString(event.getListResult());
        }

        // 3. 如果有多个对象的Result，则组装多个对象
        if (ObjectUtil.isNotNull(event.getPageResult())) {
            returnJson = JSON.toJSONString(event.getPageResult());
        }

        int length = 2_000;
        if (returnJson.length() > length) {
            log.info("json过长被截取");
            returnJson = returnJson.substring(0, 2_000);
        }
        log.info("[{}]请求结束：Result=\n{}.", resultName, returnJson);
    }
}
